<template>
  <main-content title="配送配置">
    <main-content-actions-wrapper>
      <el-button type="primary" @click="save" v-loading="saveLoading" v-has="['08050201']">保存</el-button>
      <el-button @click="selectAll">
        <template v-if="isSelectAll" @click="selectAll">全选</template>
        <template v-else @click="selectAll">全不选</template>
      </el-button>
    </main-content-actions-wrapper>
    <section class="list-wrapper" v-loading="loading">
      <address-list
          :list="provinceList"
          title="省/自治区/直辖市"
          labelKey="provinceName"
          valueKey="provinceCode"
          @click-item="clickProvinceItem"
          @click-checkbox="clickProvinceCheckBox">
      </address-list>
      <address-list
          :list="cityList"
          title="地级市"
          labelKey="cityName"
          valueKey="cityCode"
          @click-item="clickCityItem"
          @click-checkbox="clickCityCheckBox">
      </address-list>
    </section>
  </main-content>
</template>
<script lang="ts">
export default {
  name: 'MallSystemTransConfig'
}
</script>
<script setup lang="ts">
import AddressList from "./components/AddressList.vue";
import {getAreaList, getDelivers, saveDeliver} from "@/api/pointsMall"

import {IDeliverData, IDeliverItem} from "@/api/modules/pointsMall";
import {IAddressColumn, IAddressRow} from "./types/deliverySetting";
import {useMallConfig} from "@/views/pointsMall/compositions/useMallConfig";
import {exists} from "fs";
import { async } from '@antv/x6/lib/registry/marker/async';

const {mallConfig} = useMallConfig()
const provinceList = ref<IDeliverItem[]>([]) // 省
const cityList = ref<IDeliverItem[]>([])
const loading = ref<boolean>(true)
const saveLoading = ref<boolean>(false)
const isSelectAll = ref<boolean>(true)
const savedCityCodeList = ref<string[]>([])

const _getAreaList = async () => {
  loading.value = true
  const rs = await getAreaList()
  loading.value = false

  return rs.payload || []
}

const getProvinceList = async () => {
  const _provinceList = await _getAreaList()
  provinceList.value = [..._provinceList]

  echoCheck()
}

const echoCheck = () => {
  provinceList.value.forEach(pItem => {
    let trueChildrenLength = 0

    pItem.children?.forEach(cItem => {
      const target = savedCityCodeList.value.find(savedItem => savedItem === cItem.cityCode)
      cItem.exist = target ? 1 : 0

      if (target) {
        trueChildrenLength++
      }
    })

    if (trueChildrenLength === pItem.children?.length) {
      pItem.exist = 1
    } else if (trueChildrenLength === 0) {
      pItem.exist = 0
    } else {
      pItem.exist = 2
    }
  })
}

const _getDelivers = async () => {
  const rs = await getDelivers({id: mallConfig.value.id})

  if (rs.code === 200) {
    savedCityCodeList.value = rs.payload?.strCode ?? []
  }
}

const clickProvinceItem = (item: IDeliverItem, index: number) => {
  cityList.value = item.children ?? []
}

const clickProvinceCheckBox = (val: 0 | 1 | 2, item: IDeliverItem, index: number) => {
  item.exist = val
  item.children?.forEach(item => item.exist = val)

  if (val === 1) {
    // filter 用来保证cityCode存在, map导出cityCode字符串数组
    const _cityCodeList = item.children?.filter((item) => !!item.cityCode).map(item => item.cityCode) ?? []
    // 去重
    const noRepeatSet = new Set([...savedCityCodeList.value, ..._cityCodeList])
    // @ts-ignore . 会报 string|undefined[] 给 string[] 赋值的错，实际上面已经保证undefined不存在。忽略报错
    savedCityCodeList.value = [...noRepeatSet]
  } else if (val === 0) {
    item.children?.forEach(item => {
      const targetIndex = savedCityCodeList.value.findIndex(savedItem => savedItem === item.cityCode)
      if (targetIndex > -1) {
        savedCityCodeList.value.splice(targetIndex, 1)
      }
    })
  } else {
    console.log('province checkbox indeterminate', val)
  }
  console.log('savedCityCodeList', savedCityCodeList.value)
}

const clickCityItem = async (item: IDeliverItem, index: number) => {
  // console.log('地级市', item)
}

const clickCityCheckBox = (val: 0 | 1 | 2, item: IDeliverItem, index: number) => {
  item.exist = val
  const parent = provinceList.value.find(pItem => pItem.provinceCode === item.provinceCode)
  if (parent) {
    const parentChildren = parent.children ?? []
    const trueChildren = parent.children?.filter(item => item.exist === 1) ?? []
    if (trueChildren.length === parentChildren.length) {
      parent.exist = 1
    } else if (trueChildren.length === 0) {
      parent.exist = 0
    } else {
      parent.exist = 2
    }
  }

  if (val === 0) {
    const targetIndex = savedCityCodeList.value.findIndex(savedItem => savedItem === item.cityCode)
    savedCityCodeList.value.splice(targetIndex, 1)
  } else {
    if (item.cityCode) {
      savedCityCodeList.value.push(item.cityCode)
    }
  }
  console.log('savedCityCodeList', savedCityCodeList.value)
}

// const markExist = (list: IDeliverItem[]) => {
//   return list.map(item => ({
//     ...item,
//     exist: savedCityCodeList.value.find(savedItem => savedItem === item.cityCode) ? 1 : 0
//   }))
// }

const selectAll = () => {
  provinceList.value.forEach(pItem => {
    pItem.exist = isSelectAll.value ? 1 : 0

    pItem.children?.forEach(cItem => {
      cItem.exist = isSelectAll.value ? 1 : 0
    })
  })

  isSelectAll.value = !isSelectAll.value
}

const save = async () => {
  if (saveLoading.value) {
    return
  }
  saveLoading.value = true
  const _cityList: IDeliverItem[] = []
  provinceList.value.forEach(pItem => {
    pItem.children?.forEach(cItem => {
      if (cItem.exist === 1) {
        _cityList.push(cItem)
      }
    })
  })
  const _areaStr = _cityList.map(item => item.cityCode).join(',')
  // _cityList.length = 1
  console.log(_areaStr)
  try {
    const rs = await saveDeliver({mallId: mallConfig.value.id, areaStr: _areaStr})

    if (rs.code == 200) {
      ElMessage.success('保存成功')
    }
  } catch (e) {
    console.log(e)
  }

  saveLoading.value = false
}

const store = useStore();
// 监听机构
const insId = computed(() => {
  return store.state.insId.insId;
});
watch(
  () => insId,
  async () => {
   loading.value = true
    await _getDelivers()
    await getProvinceList()
    cityList.value = provinceList.value?.[0]?.children ?? []
    // markExist(cityList.value)
    loading.value = false
  },
  {
    deep: true
  }
)

onMounted(async () => {
  loading.value = true
  await _getDelivers()
  await getProvinceList()
  cityList.value = provinceList.value?.[0]?.children ?? []
  // markExist(cityList.value)
  loading.value = false
})

</script>

<style scoped>
.list-wrapper {
  display: flex;
  height: 100%;
}
</style>
